package com.doit.demo.day03.transformations;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @DATE 2022/2/16/9:34
 * @Author MDK
 * @Version 2021.2.2
 **/
public class KeyByDemo2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888);

        /*//对数据进行映射
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String line) throws Exception {
                String[] fields = line.split(",");
                String word = fields[0];
                int count = Integer.parseInt(fields[1]);
                return Tuple2.of(word, count);
            }
        });

        //对数据按照key进行分区
        //只能对Tuple类型的数据指定下标,下标从0开始
        KeyedStream<Tuple2<String, Integer>, Tuple> keyedStream = wordAndOne.keyBy("f0");*/

        SingleOutputStreamOperator<WordCount> wordAndCount = lines.map(new MapFunction<String, WordCount>() {
            @Override
            public WordCount map(String line) throws Exception {
                String[] fields = line.split(",");
                String word = fields[0];
                int count = Integer.parseInt(fields[1]);
                return new WordCount(word, count);
            }
        });
        KeyedStream<WordCount, Tuple> keyedStream = wordAndCount.keyBy("word");
        keyedStream.print();

        env.execute();
    }

    public static class WordCount{
        private String word;
        private Integer count;

        public WordCount() {
        }

        public WordCount(String word, Integer count) {
            this.word = word;
            this.count = count;
        }

        public String getWord() {
            return word;
        }

        public void setWord(String word) {
            this.word = word;
        }

        public Integer getCount() {
            return count;
        }

        public void setCount(Integer count) {
            this.count = count;
        }

        @Override
        public String toString() {
            return "(" + word + "," + count +
                    ")";
        }
    }
}
